import React from 'react';
import { Grid } from 'semantic-ui-react'
import { Link, Route} from "react-router-dom"
import DefaultContent from "../DefaultContent";
import ProgramDetail from "../Program/ProgramDetail";
import NewProgram from "../NewProgram";
import TokenManage from "../TokenManage";
import axios from "axios";
import Cookie from "react-cookies";

class AppContent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            token: Cookie.load("Token"),
            username: Cookie.load("Username")
        }
    }

    componentWillMount() {
        let infoUrl = "https://gitee.com/api/v5/user/repos?type=personal&sort=full_name&page=1&per_page=20&access_token=" + this.state.token
        let mainThis = this
        let programList = <Grid.Row>
            <div className="fetch-failed">
                Fetching...
            </div>
        </Grid.Row>
        mainThis.setState({programs: programList})
        axios.get(infoUrl)
            .then(function (response) {
                let programList = response.data.map( (p) => (
                    <Grid.Row
                        key={p.path}
                        className={"program-item "}
                    >
                        <p className="program-title">
                            <Link
                                to={"/program/" + p.path}
                            >
                                {p.name}
                            </Link>
                        </p>

                    </Grid.Row>
                ))
                mainThis.setState({programs: programList})
            })
            .catch(function () {
                let programList = <Grid.Row>
                    <div className="fetch-failed">
                        初始化项目列表失败，您可能未授权或网络不稳定，请稍后重试！
                    </div>
                </Grid.Row>
                mainThis.setState({programs: programList})
            });
    }

    render() {
        return (
            <Grid >
                <Grid.Column width={2}>
                    <Grid id="sidebar">
                        {this.state.programs}
                    </Grid>
                </Grid.Column>
                <Grid.Column width={14}>
                    <Route exact path="/" component={ DefaultContent } />
                    <Route path="/program/:pid" component={ ProgramDetail } />
                    <Route path="/new" component={ NewProgram } />
                    <Route path="/token" component={ TokenManage } />
                </Grid.Column>
            </Grid>
        )
    }
}

export default AppContent